<template>
  <div>
    <TopFilter
      ref="topFilter"
      :list="topFilterList"
      :cols="3"
      labelWidth="90"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
        ref="table"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :height="'auto'"
        :isToperInfo="false"
        :onRowSelectChange="selectChange"
        columnsRef="ysjBirthday2019100801Table"
        :onSyncTableData="tableDataChange"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls">
          <el-button :disabled="isChoice" size="small" type="primary" icon="el-icon-plus" @click="care">关爱</el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="careAll">全部关爱</el-button>
        </template>
      </FilterTable>

    <Drawer
      :visible.sync="visible"
      :title="(type == 'add' ? '关爱' : '关爱明细')"
      :width="1200"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <basePlateBirthdayDetail :queryData="queryData" :careTargetId="careTargetId" :isShowHistory="isShowHistory" :type="type" :selectedRows="selectedRows" @changeHandle="changeHandle" @close="closeHandler" />
    </Drawer>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { formatdate } from '@/utils/index';
import { qryJPBirthdayCareList } from '@/api/customerCare/saleVisit/basePlateCustomerBirthday';
import { judgeAllCareSMS } from '@/api/customerCare/saleVisit/potentialCustomerBirthday';
import basePlateBirthdayDetail from './basePlateBirthdayDetail';

export default {
  name: 'basePlateBirthday',
  mixins: [dictionary],
  components: {basePlateBirthdayDetail},
  data(){
    return {
      columns: this.createTableColumns(),
      topFilterList: this.createTopFilters(),
      fetchApi: qryJPBirthdayCareList,
      fetchParams: {careStatusList:"15921001,15921002"},
      selectedRows: [],
      isChoice: true,
      type: '',
      visible: false,
      isShowHistory: true,
      careTargetId: '',
      queryData: {}
    }
  },
  methods: {
    createTopFilters(){
      return [
        {
          type: 'INPUT_CASCADER',
          label: '客户生日开始',
          options: { titles: ['月', '日'] },
          fieldName: 'birthDayStart',
          itemList: this.getMonthDay(),
          placeholder: '客户生日开始'
        },
        {
          type: 'INPUT_CASCADER',
          label: '客户生日结束',
          options: { titles: ['月', '日'] },
          fieldName: 'birthDayEnd',
          itemList: this.getMonthDay(),
          placeholder: '客户生日结束'
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'customerNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '请输入...'
        },
        {
          type: 'RANGE_DATE',
          label: '关爱日期',
          fieldName: 'careDateStart|careDateEnd',
          dateType:"exactdaterange",
          placeholder: '关爱日期'
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '关爱状态',
          fieldName: 'careStatusList',
          placeholder: '请选择...',
          itemList: this.createDictList('1592'),
          initialValue: [15921001,15921002]
        }
      ]
    },
    createTableColumns(){
      return [
        {
          title: '序号',
          dataIndex: 'index',
          align: 'center',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '客户编号',
          dataIndex: 'customerNo',
          sorter: true,
          filter: true,
          width: 125,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '手机号',
          dataIndex: 'mobilePhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultant',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '建档日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            if(props.row.createdAt&&props.row.createdAt!=''){
              return <div>{formatdate(new Date(parseInt(props.row.createdAt)),1)}</div>;
            }
          }
        },
        {
          title: '性别',
          dataIndex: 'gender',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.gender, '1002')}</div>;
          }
        },
        {
          title: '出生日期',
          dataIndex: 'birthday',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            if(props.row.birthday&&props.row.birthday!=''){
              return <div>{formatdate(new Date(parseInt(props.row.birthday)),1)}</div>;
            }
          }
        },
        {
          title: '任务编号',
          dataIndex: 'taskNo',
          sorter: true,
          filter: true,
          width: 125,
          filterType: 'input'
        },
        {
          title: '关爱名称',
          dataIndex: 'careName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '要求完成日期',
          dataIndex: 'requiredDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            if(props.row.requiredDate&&props.row.requiredDate!=''){
              return <div>{formatdate(new Date(parseInt(props.row.requiredDate)),1)}</div>;
            }
          }
        },
        {
          title: '最后关爱日期',
          dataIndex: 'careDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            if(props.row.careDate&&props.row.careDate!=''){
              return <div>{formatdate(new Date(parseInt(props.row.careDate)),1)}</div>;
            }
          }
        },
        {
          title: '下次关爱日期',
          dataIndex: 'nextCareDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            if(props.row.nextCareDate&&props.row.nextCareDate!=''){
              return <div>{formatdate(new Date(parseInt(props.row.nextCareDate)),1)}</div>;
            }
          }
        },
        {
          title: '关爱状态',
          dataIndex: 'careStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.careStatus, '1592')}</div>;
          }
        },
        {
          title: '关爱内容',
          dataIndex: 'careContent',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '关爱失败原因',
          dataIndex: 'careFailureReason',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.careFailureReason, '1594')}</div>;
          }
        },
        {
          title: '客户反馈',
          dataIndex: 'customerFeedback',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.customerType, '1523')}</div>;
          }
        },
        {
          title: '意向级别',
          dataIndex: 'intentLevel',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.intentLevel, '1519')}</div>;
          }
        }
      ]
    },
    getMonthDay(){
      var data = [];
      for(var i=1;i<=12;i++){
        var dayByMonth = this.getDayByMonth(i,[]);
        if(i<10){
          data.push({text:i+"月",value:"0"+i,children:dayByMonth});
        }else{
          data.push({text:i+"月",value:i+"",children:dayByMonth});
        }
      }
      return data;
    },
    getDayByMonth(month,days){
      var daySize = 0;
      if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
        daySize = 31;
      }else if(month==4||month==6||month==9||month==11){
        daySize = 30;
      }else{
        daySize = 29;
      }
      for(var i=1;i<=daySize;i++){
        if(i<10){
          days.push({text:i+"号",value:"0"+i});
        }else{
          days.push({text:i+"号",value:i+""});
        }
      }
      return days;
    },
    tableDataChange (data, isFirst) {
      if (isFirst) {
        let disabledSelect = data.filter(row => (row.careStatus != 15921001 && row.careStatus != 15921002))
        this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(disabledSelect)
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      // 重新加载
      if (type === 'refresh') {
        this.fetchParams = { ...this.fetchParams };
      }
    },
    selectChange (rows){ //选中时触发的函数
      this.selectedRows = rows;
      this.isChoice = this.selectedRows.length > 0? false: true;
    },
    care(){
      this.type = 'edit';
      if(this.selectedRows.length==1){
        this.isShowHistory = true;
        this.visible = true;
        this.careTargetId = this.selectedRows[0].careTargetId+"";
      }else{
        let flagAllSend = true
        let arr = this.selectedRows
        let find = false
        for (var i = 0; i < arr.length; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i].carePlanId != arr[j].carePlanId) {
                  find = true;
                  break;
                }
            }
            if (find) break;
        }
        if(find){
          this.$message.error('选中的数据不是同一关爱计划');
          this.visible = false;
          this.isShowHistory = true;
        }else{
          for(let i =0;i<this.selectedRows.length;i++){
            if(this.selectedRows[i].careWay == '15871003'){
              flagAllSend = false
              break;
            }
          }
          if(flagAllSend){
            this.visible = true;
            this.isShowHistory = false;
          }else{
            this.$message.error('选中的数据中有不属于短信的');
            this.visible = false;
            this.isShowHistory = true;
          }
        }
      }
    },
    careAll(){
      this.type = 'edit';
      if(this.selectedRows.length==1){
        this.isShowHistory = true;
        this.careTargetId = this.selectedRows[0].careTargetId+"";
      }else{
        this.isShowHistory = false;
      }
      let birthday = this.topFilterList.find(item=>item.fieldName=='careDateStart|careDateEnd').initialValue;
      let query = {
         "careDateEnd": birthday[1],
         "careDateStart": birthday[0],
         "birthDayEnd": this.topFilterList.find(item=>item.fieldName=='birthDayEnd').initialValue,
         "birthDayStart": this.topFilterList.find(item=>item.fieldName=='birthDayStart').initialValue,
         "customerNo": this.topFilterList.find(item=>item.fieldName=='customerNo').initialValue,
         "customerName": this.topFilterList.find(item=>item.fieldName=='customerName').initialValue,
         "careStatusList": this.topFilterList.find(item=>item.fieldName=='careStatusList').initialValue.join(",")
      }
      this.queryData = query;
      this.queryData.careTypeCode = 15721004
      judgeAllCareSMS(this.queryData).then(res=>{
        if(res.resultCode ==200){
           if(res.data.status == 0){
              this.$message.error('暂无数据')
              this.visible = false;
            }else if(res.data.status == 2){
              this.$message.error('选中的数据中有不属于短信的')
              this.visible = false;
            }else if(res.data.status == 1){
              this.queryData.careTargetIdList = res.data.careTargetIdList
              this.visible = true;
            }else if(res.data.status == 3){
              this.$message.error('选中的数据不属于同一个计划')
              this.visible = false;
            }
        }
      })
    },
    submitCare(){
      let param = [];
      this.selectedRows.map(obj=>{
        let data = {carePlanId:obj.carePlanId,recordVersion:obj.recordVersion};
        param.push(data);
      });
    }
  }
}
</script>
